package com.pubg.servlet;

import com.pubg.entity.Product;
import com.pubg.service.ProductService;
import com.pubg.service.ProductTypeService;
import com.pubg.service.impl.ProductServiceImpl;
import com.pubg.service.impl.ProductTypeServiceImpl;
import com.pubg.util.StringUtil;
import com.pubg.vo.PageVo;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

@WebServlet(name = "ProductServlet",urlPatterns = "/product")
public class ProductServlet extends HttpServlet {
    private ProductService productService = new ProductServiceImpl();
    private ProductTypeService productTypeService = new ProductTypeServiceImpl();
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        String opr = request.getParameter("opr");
        if (opr.equals("typeList")){
            doTypeList(request,response,out);
        }else if (opr.equals("add")){
            doAdd(request,response,out);
        }else if(opr.equals("productList")){
            doProductList(request,response,out);
        }else if (opr.equals("del")){
            int id = Integer.parseInt(request.getParameter("id"));
            if (productService.del(id)){
                out.print("<script type='text/javascript'>alert('商品下架成功！');</script>");
                request.getSession().removeAttribute("pageVo");
                request.getRequestDispatcher("loginAfter/backManage/backIndex.jsp").forward(request,response);
            }else{
                out.print("<script type='text/javascript'>alert('商品下架失败！');</script>");
                request.getRequestDispatcher("loginAfter/backManage/backIndex.jsp").forward(request,response);
            }

        }
    }

    /**
     * 获取商品列表
     * 分组获取
     * @param request
     * @param response
     * @param out
     */
    private void doProductList(HttpServletRequest request, HttpServletResponse response, PrintWriter out) throws ServletException, IOException {

        //商品内容分组
        String currPageNo = request.getParameter("currPageNo");
        String pageSize = request.getParameter("pageSize");
        String name = request.getParameter("name");
        int totalCount = productService.getCount(name);
        PageVo<Product> pageVo = new PageVo<>(currPageNo,pageSize,totalCount);
        List<Product> list = productService.getPage(
                pageVo.getCurrPageNo(),
                pageVo.getPageSize(),name);
        pageVo.setDataList(list);
        request.getSession().setAttribute("pageVo",pageVo);
        int currNo = pageVo.getCurrPageNo();
        int pageS = pageVo.getPageSize();
        //分组数据Id
        int index = (currNo-1)*pageS+1;
        request.getSession().setAttribute("index",index);
        request.getRequestDispatcher("loginAfter/backManage/backIndex.jsp").forward(request,response);
    }

    /**
     * 添加商品
     * @param request
     * @param response
     * @param out
     */
    private void doAdd(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
        //文件上传开始
        String name="";
        int type=0;
        float price=0;
        String description = "";
        String fileName ="";
        int stock = 0;
        //判断是否上传成功
        Boolean isFileUpload = false;
        //上传路径
        String filePath = request.getServletContext().getRealPath("/upload/images");
        File file = new File(filePath);
        if (!file.exists()){
            file.mkdirs();//连续创建文件夹
        }
        DiskFileItemFactory itemFactory = null;
        ServletFileUpload fileUpload = null;
        try{
            //加载文件工厂
            itemFactory = new DiskFileItemFactory();
            //设置缓冲区大小
            itemFactory.setSizeThreshold(1024*10);
            //设置临时存储目录
            File tempDir = new File(filePath+"/temp");
            if (!tempDir.exists()){
                tempDir.mkdir();//
            }
            //设置临时文件存放的位置
            itemFactory.setRepository(tempDir);

            //创建上传文件对象
            fileUpload = new ServletFileUpload(itemFactory);
            //设置上传最大限制
            fileUpload.setFileSizeMax(1024*1024*10);
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            if (isMultipart){
                //文件上传表单
                //得到表单中所有的项
                List<FileItem> list =  fileUpload.parseRequest(request);
                Iterator<FileItem> iterator = list.iterator();
                while (iterator.hasNext()){
                    FileItem item = iterator.next();
                    if (item.isFormField()){ // 普通表单
                        String fieldName = item.getFieldName();
                        if ("name".equals(fieldName)){
                            name = item.getString("UTF-8");
                        }
                        if ("productType".equals(fieldName)){
                            type = Integer.parseInt(item.getString("UTF-8"));
                        }
                        if ("price".equals(fieldName)){
                            price = Float.parseFloat(item.getString("UTF-8"));
                        }
                        if ("description".equals(fieldName)){
                            description = item.getString("UTF-8");
                        }
                        if ("stock".equals(fieldName)){
                            stock = Integer.parseInt(item.getString("UTF-8"));
                        }

                    }else{ //文件表单
                        //获取上传文件的名称
                        fileName = item.getName();
                        //获取文件后缀
                        String ext = fileName.substring(fileName.indexOf(".")+1);
                        //设置上传文件的类型
                        List<String> fileType = Arrays.asList("jpg","png","gif","jpeg");
                        if (fileType.contains(ext)){//符合格式 上传
                            fileName= StringUtil.easyPicName(fileName,ext);
                            File saveFile = new File(
                                    filePath, fileName);
                            //写入到服务器
                            item.write(saveFile);
                            isFileUpload = true;

                        }else{//不符合格式
                            isFileUpload = false;
                            out.println("<script type='text/javaScript'> " +
                                    "alert('文件格式不符合图片格式！');" +
                                    "location.href='loginAfter/backManage/backIndex.jsp';" +
                                    "</script>");
                        }
                    }
                }

            }else {
                //普通表单
                isFileUpload = false;
                out.println("<script type='text/javaScript'> " +
                        "alert('您没有上传文件！');" +
                        "location.href='loginAfter/backManage/backIndex.jsp';" +
                        "</script>");
            }
        }catch (FileUploadException e){
            try{
                isFileUpload = false;
                throw new Exception("文件上传失败，单个文件太大，上传限制是："+fileUpload.getSizeMax()+"KB");
            }catch (Exception e1){
                e1.printStackTrace();
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (isFileUpload){//保存数据
                Product product = new Product();
                product.setName(name);
                product.setCategoryLevel(type);
                product.setPrice(price);
                product.setDescription(description);
                product.setStock(stock);
                product.setFileName(fileName);
                if (productService.add(product)){
                    request.getSession().removeAttribute("typeList");
                    out.println("<script type='text/javaScript'> " +
                            "alert('文件上传成功！');" +
                            "location.href='loginAfter/backManage/backIndex.jsp';" +
                            "</script>");
                }else {
                    out.println("<script type='text/javaScript'> " +
                            "alert('文件上传失败！');" +
                            "location.href='loginAfter/backManage/backIndex.jsp';" +
                            "</script>");
                }
            }else {
                out.println("<script type='text/javaScript'> " +
                        "alert('文件上传失败！');" +
                        "location.href='loginAfter/backManage/backIndex.jsp';" +
                        "</script>");
            }
        }
    }

    /**
     * 获取分类列表
     * @param request
     * @param response
     * @param out
     */
    private void doTypeList(HttpServletRequest request, HttpServletResponse response, PrintWriter out) throws ServletException, IOException {
        request.getSession().setAttribute("typeList",productTypeService.getList());
        request.getRequestDispatcher("loginAfter/backManage/backIndex.jsp").forward(request,response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
